package com.hefan.oms.task;

import com.hefan.live.bean.LiveLog;
import com.hefan.live.itf.LiveLogService;
import com.hefan.oms.itf.AnchorTicketMonthService;
import com.hefan.oms.itf.InComeService;
import com.hefan.schedule.model.ScheduleExecuteRecord;
import com.hefan.schedule.model.ScheduleServer;
import com.hefan.schedule.service.IScheduleExecuteRecordService;
import com.hefan.schedule.service.IScheduleTaskDeal;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wangchao on 2016/12/28.
 * 统计前一天主播收入：月表、每次直播收入和历史收入
 */

@Service("anchorLiveTask")
public class AnchorLiveIncomeTask implements IScheduleTaskDeal {

  private static Logger logger = LoggerFactory.getLogger(AnchorLiveIncomeTask.class);

  @Resource
  private IScheduleExecuteRecordService scheduleExecuteRecordService;
  @Resource
  private LiveLogService liveLogService;
  @Resource
  private AnchorTicketMonthService anchorTicketMonthService;

  @Resource
  private InComeService inComeService;

/**
   * 主播间收入定时任务 0 10 2 * * ?
   *
   * @param scheduleServer
   * @author wangchao
   * @version 1.0.0
   * @since 2016/10/31 下午12:25:16
   */

  @Override
  public boolean execute(ScheduleServer scheduleServer) {
    ScheduleExecuteRecord scheduleExecuteRecord = new ScheduleExecuteRecord();
    scheduleExecuteRecord.setExecuteTime(new Date());
    long startTime = System.currentTimeMillis();
    boolean rst = true;
    //1.统计收入时间区间比例
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH,-1);
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
    DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
    String end = dateFormat2.format(cal.getTime());
    String start = dateFormat.format(cal.getTime());
    int failCount = 0;
    int successCount = 0;
    try {
      //2.查询前一天所有关播
      List<LiveLog> list=liveLogService.getLiveLogByEndTime(start,end);
      if (!CollectionUtils.isEmpty(list)) {
        //3.遍历每次直播收入：统计直播间
        for (LiveLog liveLog : list) {
          List<Map<String, Object>> income = inComeService.getTotalByLiveUuid(liveLog.getLiveUuid());
          if (!org.springframework.util.CollectionUtils.isEmpty(income)) {
            for (Map<String, Object> map : income) {
              if (org.springframework.util.CollectionUtils.isEmpty(map) || !map.containsKey("type") || !map.containsKey("hefanNum")) {
                break;
              }
              long balance = map.get("hefanNum") == null ? 0 : Long.parseLong(map.get("hefanNum").toString());
              if ("1".equals(map.get("type").toString())) {
                liveLog.setTicketCount(balance);
                liveLog.setFalseTicketCount(0);
              } else {
                liveLog.setFalseTicketCount(balance);
                liveLog.setTicketCount(0);
              }
              anchorTicketMonthService.dealAnchorLiveDetail(liveLog);
            }
          }
        }
      }
      successCount++;
    } catch (Exception e) {
      logger.error("主播间收入异常", e);
      rst = false;
      failCount++;
    }
    long endTime = System.currentTimeMillis();
    scheduleExecuteRecord.setConsumingTime((endTime - startTime));
    scheduleExecuteRecord.setNextExecuteTime(scheduleServer.getNextRunStartTime());
    scheduleExecuteRecord.setTaskType(scheduleServer.getBaseTaskType());
    scheduleExecuteRecord.setStatus(rst ? (short) 1 : (short) 2);
    scheduleExecuteRecord.setExecuteResult(String.format("主播月收入，成功处理%s条，失败%s条", successCount, failCount));
    scheduleExecuteRecord.setHostName(scheduleServer.getHostName());
    scheduleExecuteRecord.setIp(scheduleServer.getIp());
    scheduleExecuteRecordService.addScheduleExecuteRecord(scheduleExecuteRecord);
    return true;
  }
}

